#include "../include/RouteManager.h"

#include "../include/RouteNode.h"

#include "Poco/HashMap.h"
#include "Poco/Array.h"

#include "Poco/SharedPtr.h"

#include <iostream>


namespace Reactor
{
#define ROUTE_FRAGMENT_COUNT 10
	struct MOUDLE_API RouteFragment
	{
		Poco::HashMap<std::string, std::shared_ptr<RouteNode>> _hashRoute;
	};


	struct RouteManagerPrivate
	{
		Poco::Array<RouteFragment, ROUTE_FRAGMENT_COUNT> _hashRouteArray;
	};

	void RouteManager::add(std::shared_ptr<RouteNode> _routeNode)
	{
		int _index = index(_routeNode->request());
		d->_hashRouteArray[_index]._hashRoute.insert
			(
				Poco::HashMapEntry<std::string, std::shared_ptr<RouteNode>>(_routeNode->request(), _routeNode)
			);
	}

	std::shared_ptr<RouteNode> RouteManager::route(const std::string& _routeKey) const
	{
		int _index = index(_routeKey);
		auto iter = d->_hashRouteArray[_index]._hashRoute.find(_routeKey);
		if (iter == d->_hashRouteArray[_index]._hashRoute.end())
		{
			return std::shared_ptr<RouteNode>();
		}
		return iter->second;
	}

	int RouteManager::index(const std::string& _routeKey)const
	{
		return Poco::hash(_routeKey) % ROUTE_FRAGMENT_COUNT;
	}

	RouteManager::RouteManager()
	{
		d.reset(new RouteManagerPrivate);
	}

}
